package com.zackratos.navbarexist.navbarexist

import android.content.Context
import android.os.Build
import android.util.DisplayMetrics
import android.view.View
import android.view.WindowManager
import androidx.annotation.RequiresApi
import androidx.fragment.app.FragmentActivity

/**
 * @Author   : zackratos
 * @Date     : 2021/8/23 2:01 下午
 * @email    : zhangwenchao@soulapp.cn
 * @Describe :
 */
fun FragmentActivity.navBarExist(block: ((Boolean) -> Unit)? = null) {
    navBarHeight { block?.invoke(it > 0) }
}

fun FragmentActivity.navBarHeight(block: ((Int) -> Unit)? = null) {
    val height = _navBarHeight
    if (height >= 0) {
        block?.invoke(height)
        return
    }
    val c1 = child1 ?: return
    if (c1.height > 0) {
        c1.putNavBarHeight(landscape, block)
        return
    }
    c1.post {
        c1.putNavBarHeight(landscape, block)
    }
}

val FragmentActivity.navBarExist: Boolean
    get() = navBarHeight > 0

/**
 *  获取当前 Activity 的导航栏高度
 *  必须在 [navBarHeight] 方法之后调用，否则无效（为 0）
 */
val FragmentActivity.navBarHeight: Int
    get() {
        val height = _navBarHeight
        if (height > 0) {
            return height
        }
        return 0
    }

private val FragmentActivity._navBarHeight: Int
    get() {
        if (!versionO) {
            return lowVersionNavBarHeight
        }
        val c1 = child1 ?: return -1
        val initialization: Boolean = (c1.getTag(R.id.zackratos_navigation_bar_height_initialization) ?: false) as Boolean
        if (initialization) {
            return (c1.getTag(R.id.zackratos_navigation_bar_height) ?: -1) as Int
        }
        return -1
    }

private fun View.putNavBarHeight(landscape: Boolean, block: ((Int) -> Unit)?) {
    val height = if (landscape) marginRight else marginBottom
    setTag(R.id.zackratos_navigation_bar_height_initialization, true)
    setTag(R.id.zackratos_navigation_bar_height, height)
    block?.invoke(height)
}

private val Context.lowVersionNavBarHeight: Int
    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    get() {
        val wm = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val display = wm.defaultDisplay
        val realDisplayMetrics = DisplayMetrics()

        display.getRealMetrics(realDisplayMetrics)

        val displayMetrics = DisplayMetrics()
        display.getMetrics(displayMetrics)

        if (landscape) {
            return realDisplayMetrics.widthPixels - displayMetrics.widthPixels
        }
        return realDisplayMetrics.heightPixels - displayMetrics.heightPixels
    }